const crypto = require('crypto')
const key = 'fwaiehfiidiake@9'

// 设置密钥
const create = (str = '') => {
  if (typeof str === 'object') {
    str = JSON.stringify(str)
  }
  const hmac = crypto.createHmac('sha256', key)
    .update(str)
  return hmac.digest('hex')
}

// 检查是否合格
const isSerious = (user, data = '') => {
  return data === create(user)
}

const auth = async (ctx, next) => {
  let token = ctx.header.authorization || 'e30='
  token = Buffer(token, 'base64').toString()
  await next()
  console.log(ctx.path)
  /*
	try {
		token = JSON.parse(token)
    const now = Date.now()
    if (!token.username || !isSerious(token, token.data || token.expire > now)) {
      // throw new Error('token is bad')
      await next()
    } else {
      ctx.user = {
        username: token.username,
        _id: token._id,
        expire: token.expire,
      }
      await next()
    }
		await next()
	} catch(e) {
		ctx.status = 401
		ctx.body = {
			code: 401,
			msg: 'Not Alloewd Access, Please Login Again Or Check Your Promsition',
			data: [],
		}
	}
  */
}

module.exports = auth